package com.bootcamp.s3_1013.database.utils;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @program: myClassCode
 * @description: use dbcp connection pool
 * @author: Keyu Li
 * @create: 2021-10-19 10:04
 **/

public class DBCPUtils {

    static DataSource dataSource;

    //initial connection pool
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("config/dbcp.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }
}
